package capricornus.utils.pool
{
	import capricornus.utils.roughtime.RoughTimer;
	import capricornus.utils.roughtime.RoughTimerEvent;
	
	import flash.utils.Dictionary;

	/**
	 * 资源延迟释放控制器
	 * 对于一些图片资源要延迟一些时间再释放，防止重复加载
	 * @author Administrator
	 * 
	 */	
	public class ResDelayFreeController
	{
		/**
		 * 释放函数 
		 */		
		private var _freeHandler:Function;
		/**
		 * 定时释放timer 
		 */		
		private var _roughTimer:RoughTimer;
		
		/**
		 * 要释放的资源列表
		 */		
		private var _dictFrees:Dictionary;
		
		public function ResDelayFreeController( freeHandler:Function )
		{
			_freeHandler = freeHandler;
			init();
		}
		
		private function init():void
		{
			_roughTimer = new RoughTimer( 2000 );
			_roughTimer.addEventListener( RoughTimerEvent.TIMER, onTimeToFree );
			_dictFrees = new Dictionary();
		}
		
		public function free( url:String ):void
		{
			if( url=="" || url==null ) return;
			if( !_roughTimer.running )
			{
				_roughTimer.reset();
				_roughTimer.start();
			}
			if( _dictFrees[url]==null )
			{
				trace( "want free: ", url );
				var fi:FreeItem = new FreeItem();
				fi.url = url;
				_dictFrees[url] = fi;
			}
		}
		
		public function stopFree( url:String ):void
		{
			if( _dictFrees[url] != null )
			{
				trace( "stop free: ", url );
				delete _dictFrees[url];
				
				if( _roughTimer.running )
				{
					var b:Boolean = true; //_dictFrees里面是否已经没有元素了
					for( var s:String in _dictFrees )
					{
						b = false;
						break;
					}
					if( b )
					{
						_roughTimer.stop();
					}
				}
			}
		}
		/**
		 * 定时检查函数 
		 * @param e
		 * 
		 */		
		private function onTimeToFree( e:RoughTimerEvent ):void
		{
			var fi:FreeItem;
			for( var url:String in _dictFrees )
			{
				fi = _dictFrees[url];
				fi.frame--;
				if( fi.frame <= 0 )
				{
					delete _dictFrees[url];
					_freeHandler( url );
				}
			}
		}
	}
}


class FreeItem
{
	/**
	 * 要释放的资源路径 
	 */	
	public var url:String;
	/**
	 * 延迟释放的RoughTimer帧数，默认是2，当0的时候资源将释放
	 * 由于RoughTimer设置的时间是2000，所有资源将在2000~4000时间内被释放
	 */	
	public var frame:int = 2;
	
	/**
	 * 重置延迟时间 
	 * 
	 */	
	public function reset():void
	{
		frame = 2;
	}
}













